package com.tq.util;

import com.alibaba.fastjson.JSONArray;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description:构建jsonTree
 * @author zy 2018-05-28
 * @param <T>
 *            T：需要构建树结构的bean
 */
public class TreeBuilder<T extends TreeNode<T>> {

	List<T> nodes = new ArrayList<>();

	public TreeBuilder(List<T> nodes) {
		super();
		if (nodes != null && nodes.size() > 0) {
			this.nodes = nodes;
		}
	}

	/**
	 * 构建树返回List
	 * 
	 * @return
	 */
	public List<T> buildJSONTree() {
		return buildTree();
	}

	/**
	 * 构建json树返回jsonString
	 * 
	 * @return
	 */
	public String buildJSONStringTree() {
		List<T> nodeTree = buildTree();
		return JSONArray.toJSONString(nodeTree);
	}

	// 构建树形结构
	public List<T> buildTree() {
		List<T> treeNodes = new ArrayList<>();
		List<T> rootNodes = getRootNodes();
		for (T rootNode : rootNodes) {
			buildChildNodes(rootNode);
			treeNodes.add(rootNode);
		}
		return treeNodes;
	}

	// 递归子节点
	private void buildChildNodes(T node) {
		List<T> children = getChildNodes(node);
		if (!children.isEmpty()) {
			for (T child : children) {
				buildChildNodes(child);
			}
			node.setChildren(children);
		}
	}

	// 获取父节点下所有的子节点
	private List<T> getChildNodes(T pnode) {
		List<T> childNodes = new ArrayList<>();
		for (T n : nodes) {
			if (pnode.getId().equals(n.getPid())) {
				childNodes.add(n);
			}
		}
		return childNodes;
	}

	// 判断是否为根节点
	private boolean rootNode(T node) {
		boolean isRootNode = true;
		for (T n : nodes) {
			if (n.getId().equals(node.getPid())) {
				isRootNode = false;
				break;
			}
		}
		return isRootNode;
	}

	// 获取集合中所有的根节点
	private List<T> getRootNodes() {
		List<T> rootNodes = new ArrayList<>();
		for (T n : nodes) {
			if (rootNode(n)) {
				rootNodes.add(n);
			}
		}
		return rootNodes;
	}

}
